import random
from io import BytesIO

from django import forms
from django.core.validators import RegexValidator
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

from app01 import models
from script.cos_sts_demo import temp_sts_token
from tracker.settings import TEMPLATE_ID
from utils.tencent.sms import send_sms_single
# Create your views here.
from utils.verify_code.verify_code import create_validate_code





class RegisterModelForm(forms.ModelForm):
    mobile_phone = forms.CharField(label='手机号',validators=[
        RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$','手机号格式错误'),])

    passwd = forms.CharField(label='密码', widget=forms.PasswordInput())

    confirm_passwd = forms.CharField(label='重复密码', widget=forms.PasswordInput(
        attrs={'class':'form-control','placeholder':'请再次输入密码'}),)

    code = forms.CharField(label='验证码')


    class Meta:
        model = models.UserInfo
        #   原models里定义的顺序 加上上面的 RegisterModelForm中新增的顺序
        # fields = "__all__"
        # 重新自定义顺序
        fields = ['user_name','email','passwd','confirm_passwd','mobile_phone','code']

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)






def index(request):
    return  render(request, 'index_001.html')


def verfiy_code_sms_genter():
    # generate message's four nums's verfiy_code
    verfiy_code_sms = random.randint(1000, 9999)

    return verfiy_code_sms


def sms(request,phone_num = 18361077805):
    # send_sms_single(phone_num, template_id, template_param_list):
    # """
    # 单条发送短信
    # :param phone_num: 手机号
    # :param template_id: 腾讯云短信模板ID
    # :param template_param_list: 短信模板所需参数列表，例如:【验证码：{1}，描述：{2}】，则传递参数 [888,666]按顺序去格式化模板
    # :return:
    # """
    verfiy_codes_sms = verfiy_code_sms_genter()
    # phone_num = 18361077805

    template_id = TEMPLATE_ID['register']
    if not template_id:
        return HttpResponse('temlpates_id not found!')
    template_param_list = [verfiy_codes_sms, ]

    res = send_sms_single(phone_num,template_id,template_param_list)
    if not res['result']:
        return HttpResponse('send message sucess')
    else :
        return HttpResponse('error')





def verify_code_genter(request):
    img, str1 = create_validate_code()
    verify_code_img = img
    verify_code = str1.lower()
    print(verify_code)
    # request.session['verfiy_code_strap'] = verify_code
    fp = BytesIO()
    verify_code_img.save(fp, 'png')
    return HttpResponse(fp.getvalue(), content_type='image_png')


def Sign_up(request):
    if request.method=="GET":
        return render(request, 'Sing_up_00001.html')
    elif request.method=="POST":
        tel_num = request.POST.get('phonenumber')
        # print(type(tel_num))
        # print(tel_num)
        # sms(request,tel_num)
        return HttpResponse('success')



def Register(request):
    form = RegisterModelForm()

    if request.method=="GET":
        return render(request, 'app01/Register.html', locals())
        # return render(request,'Register.html',{'form':form})

    elif request.method=="POST":

        return HttpResponse('Register success')


def cos_upload(request):
    if request.method == 'GET':
        return render(request,'app01/cos_js_file.html')
    # if request.method == 'POST':
    # bucket = request.POST.get('bucket')
    # region =  request.POST.get('region')

    # bucket = request.POST.get('bucket')
    response = temp_sts_token(bucket='18361077805-1603095459-1303881619',region='ap-nanjing')
    print('ok')
    # return JsonResponse(response)
    #临时凭证生成
    return  JsonResponse({'status':'very_good'})


        # return JsonResponse({'data':{'s_id':'123','s_key':'123'},'status':True})